<?php
declare(strict_types=1);

namespace App\Service;

use App\Model\AdminModel;
use Hyperf\Contract\SessionInterface;
use Hyperf\Di\Annotation\Inject;
use Donjan\Casbin\Enforcer;

class AdminService extends BaseService
{
    /**
     * @Inject
     * @var SessionInterface
     */
    protected $session;

    /**
     * 用户登录
     *
     * @param string $username
     * @param string $password
     * @return string[]
     */
    public function login(string $username, string $password): array
    {
        $admin = adminModel::query()->where('username', $username)->first();
        if (!$admin) {
            return [
                'state' => 'fail',
                'msg'   => '用户不存在',
            ];
        }
        // 密码验证
        if (genPsw($password, $admin->salt) != $admin->password) {
            return [
                'state' => 'fail',
                'msg'   => '登录密码错误',
            ];
        }

        $this->session->set('admin_id', $admin->id);

        return [
            'state' => 'success',
            'msg'   => '登录成功',
        ];
    }

    public function queryById(int $id)
    {
        return adminModel::query()->find($id);
    }

    public function currentLogin()
    {
        $id = $this->session->get('admin_id');
        return $this->queryById($id);
    }

    public function passwordChange(string $oPsw, string $nPsw, string $aPsw)
    {
        $res = [
            'state' => 'fail',
            'msg' => '操作失败'
        ];
        if (!$oPsw) {
            $res['msg'] = '';
            return $res;
        }
        $admin = $this->currentLogin();
        if (!$admin || genPsw($oPsw, $admin->salt) != $admin->password) {
            $res['msg'] = '密码认证失败';
        }
        if (!$nPsw) {
            $res['msg'] = '';
            return $res;
        }
        if (!$aPsw) {
            $res['msg'] = '';
            return $res;
        }
        if ($nPsw != $aPsw) {
            $res['msg'] = '确认密码与新密码不一致';
        }

        $salt = random(16, 3, '0123456789abcdefghijklmnopqrstuvwxyz~!@#$%^&*()_+<>,.');
        $admin->password = genPsw($nPsw, $salt);
        $admin->salt = $salt;
        $admin->save();

        $res['state'] = 'success';
        $res['msg'] = '密码修改成功';
        return $res;
    }

    public function logout()
    {
        $this->session->forget('admin_id');

        return [
            'state' => 'success',
            'msg' => '注销登录成功'
        ];
    }

    public function indexList(array $params, array $columns = ['*'])
    {
        $lists = AdminModel::query()->where($params)->select($columns);

        return $lists;
    }
}